package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.xml.internal.bind.v2.TODO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;



    @PostMapping("/login")
    public Result login(@RequestBody Employee employee, HttpServletRequest request){

        String password = employee.getPassword();
        String username = employee.getUsername();

        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Employee::getUsername,username);

        Employee one = employeeService.getOne(wrapper);

        if (one==null)
            return Result.error("用户不存在");

        if (!one.getPassword().equals(password))
            return Result.error("密码不正确");

        if (one.getStatus()==0)
            return Result.error("用户被禁用");

        request.getSession().setAttribute("employee",one.getId());

        //TODO:登录成功记得存入redis

        return Result.success(one);
    }

    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){

        //TODO:清理redis缓存
        request.getSession().removeAttribute("employee");

        return Result.success("退出成功");
    }

    @PostMapping
    public Result<String> save(@RequestBody Employee employee){

        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employeeService.save(employee);

        return Result.success("添加成功");
    }


    @GetMapping("/page")
    public Result getByPage(Integer page, Integer pageSize,String name){

        Page<Employee> emppage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Employee> empwrapper = new LambdaQueryWrapper<>();


        empwrapper.like(!StringUtils.isEmpty(name),Employee::getName,name);

        empwrapper.orderByAsc(Employee::getUpdateTime);

        emppage = employeeService.page(emppage, empwrapper);

        return Result.success(emppage);

    }

    @PutMapping
    public Result<String> update(@RequestBody Employee employee){


        employeeService.updateById(employee);

        return Result.success("修改成功");

    }

    @GetMapping("/{id}")
    public  Result getById(@PathVariable Long id){

        Employee employee = employeeService.getById(id);

        return Result.success(employee);
    }

}
